// 独立调色板 dom结构
const colorPalette = document.createElement('div')
colorPalette.classList.add('color-palette-library')
colorPalette.style.display = 'none'
    // <div class="title">
    // < span > 字体颜色</span >
    //     <img src="${require('@/assets/icons/style/get-color.png')}" />
    //     <input type="color" id="text-color" class="select-color" name="head" value="#e66465" />
    // </div >
    // <div class="fast-wrap text-list">
    //     ${generateColorList('text')}
    // </div>
colorPalette.innerHTML = `
    <div class="title">
        <span>边框颜色</span>
        <img src="${require('@/assets/icons/style/get-color.png')}" />
        <input type="color" id="border-color" class="select-color " name="head" value="#e66465" />
    </div>
    <div class="fast-wrap border-list">
        ${generateColorList('border')}
    </div>
    <div class="title">
        <span>背景颜色</span>
        <img src="${require('@/assets/icons/style/get-color.png')}" />
        <input type="color" id="bg-color" class="select-color" name="head" value="#e66465" />
    </div>
    <div class="fast-wrap bg-list">
        ${generateColorList('bg')}
    </div>
    <div class="line-nodel"></div>
    <div id="reset-color">恢复默认</div>
`

// 调色板dom & 调色板父级
// const textColor = colorPalette.querySelectorAll('#text-color')[0]
const borderColor = colorPalette.querySelectorAll('#border-color')[0]
const bgColor = colorPalette.querySelectorAll('#bg-color')[0]
const resetColor = colorPalette.querySelectorAll('#reset-color')[0]
const colorPaletteDom = colorPalette

let chunkDom = null
let activeEditor = null
let defaultClass = null
let top = 26
let activeDom = null

// 初始化调色板
function initPallette(dom, editor,defaultClass,offsetTop) {
    top = offsetTop || 26
    chunkDom = dom
    activeEditor = editor
    defaultClass = defaultClass
}

// 调色板图标点击事件
function colorPaletteClick(e,optionActive,fn){
    activeDom = optionActive
    if (colorPaletteDom.style.display == 'none') {
        colorPaletteDom.style.display = 'block'
        colorPaletteDom.style.transform = 'scale(1)'
        colorPaletteDom.style.opacity = '1'
        colorPaletteDom.style.top = top + 'px'
        // isShowColorPalette = true
        // 获取高亮块的颜色用于调色板选中回显
        const color = rgbToHex(chunkDom.style.backgroundColor || 'rgb(254, 248, 232)')
        const parentNode = colorPaletteDom.querySelector('.bg-list')
        for (let i = 0; i < parentNode.children.length; i++) {
            const childNode = parentNode.children[i];
            // 检查子节点是否是元素节点（不是文本节点或注释节点）
            if (childNode.getAttribute('data-color') == color) {
                // 修改子节点的class
                childNode.className = 'active-bg-color'; // 替换你的class名
            } else {
                childNode.className = 'hidden-bg-color'; // 替换你的class名
            }
        }
        fn(true)
    } else {
        colorPaletteDom.style.display = 'none'
        colorPaletteDom.style.transform = 'scale(.8)'
        colorPaletteDom.style.opacity = '0'
        colorPaletteDom.style.top = top + 'px'
        // isShowColorPalette = false
        fn(false)
    }
}
// 关闭调色板显示
function closeColorPalette() {
    colorPaletteDom.style.display = 'none';
    colorPaletteDom.style.transform = 'scale(.8)';
    colorPaletteDom.style.opacity = '0';
    if (activeDom){
        activeDom.style.transform = 'rotate(0deg)';
    }
}
// 背景色rgb转hex
function rgbToHex(rgbString) {
    const rgb = rgbString.match(/\d+/g).map(Number);
    return "#" + ((1 << 24) + (rgb[0] << 16) + (rgb[1] << 8) + rgb[2]).toString(16).slice(1);
}


// 调色板颜色点击事件
colorPaletteDom.addEventListener('click', (e) => {
    let effectiveDom = null
    let effectiveChunk = ['text-list', 'border-list', 'bg-list']
    // 向上找块级元素，最高三层
    if (e.target && effectiveChunk.includes(e.target.classList.item(1))) {
        effectiveDom = e.target.classList.item(1)
    } else if (e.target && effectiveChunk.includes(e.target.parentNode.classList.item(1))) {
        effectiveDom = e.target.parentNode.classList.item(1)
    } else if (e.target && effectiveChunk.includes(e.target.parentNode.parentNode.classList.item(1))) {
        effectiveDom = e.target.parentNode.parentNode.classList.item(1)
    }
    if (e.target.localName == 'span' && effectiveDom === 'bg-list') {
        const parentNode = e.target.parentNode
        for (let i = 0; i < parentNode.childNodes.length; i++) {
            const childNode = parentNode.childNodes[i];
            // 检查子节点是否是元素节点（不是文本节点或注释节点）
            if (childNode.nodeType === 1) {
                // 修改子节点的class
                childNode.className = 'hidden-bg-color'; // 替换你的class名
            }
        }
        const color = e.target.dataset.color || e.target.parentNode.dataset.color
        e.target.classList.remove('hidden-bg-color')
        e.target.classList.add('active-bg-color')
        let styleAttri = chunkDom.getAttribute('data-mce-style') || ''
        styleAttri = replaceOrAppendCssValue(styleAttri, 'background-color', color)
        activeEditor.dom.setAttribs(chunkDom, {
            'data-mce-style': styleAttri,
            'style': styleAttri
        })
    } else if ((e.target.localName == 'span' || e.target.localName == 'img') && effectiveDom === 'border-list') {
        const color = e.target.dataset.color || e.target.parentNode.dataset.color
        console.log(color, effectiveDom, '调色板点击事件')

        let styleAttri = chunkDom.getAttribute('data-mce-style') || ''
        styleAttri = replaceOrAppendCssValue(styleAttri, 'border-color', color)
        activeEditor.dom.setAttribs(chunkDom, {
            'data-mce-style': styleAttri,
            'style': styleAttri
        })
    } 
    // else if (e.target.localName == 'span' && effectiveDom === 'text-list') {
    //     const color = e.target.dataset.color || e.target.parentNode.dataset.color

    //     let styleAttri = chunkDom.getAttribute('data-mce-style') || ''
    //     styleAttri = replaceOrAppendCssValue(styleAttri, 'color', color)
    //     activeEditor.dom.setAttribs(chunkDom, {
    //         'data-mce-style': styleAttri,
    //         'style': styleAttri
    //     })
    // }
    e.stopPropagation()
})
// 调色板背景seclet 事件
bgColor.addEventListener('input', (e) => {
    const color = e.target.value
    let styleAttri = chunkDom.getAttribute('data-mce-style') || ''
    styleAttri = replaceOrAppendCssValue(styleAttri, 'background-color', color)
    activeEditor.dom.setAttribs(chunkDom, {
        'data-mce-style': styleAttri,
        'style': styleAttri
    })
})
// 调色板字体seclet 事件
// textColor.addEventListener('input', (e) => {
//     const color = e.target.value
//     let styleAttri = chunkDom.getAttribute('data-mce-style') || ''
//     styleAttri = replaceOrAppendCssValue(styleAttri, 'color', color)
//     activeEditor.dom.setAttribs(chunkDom, {
//         'data-mce-style': styleAttri,
//         'style': styleAttri
//     })
// })
// 调色板边框seclet 事件
borderColor.addEventListener('input', (e) => {
    const color = e.target.value
    let styleAttri = chunkDom.getAttribute('data-mce-style') || ''
    styleAttri = replaceOrAppendCssValue(styleAttri, 'border-color', color)
    activeEditor.dom.setAttribs(chunkDom, {
        'data-mce-style': styleAttri,
        'style': styleAttri
    })
})
// 重置高亮块样式
resetColor.addEventListener('click', () => {
    if (Object.keys(defaultClass||{}).length){
        activeEditor.dom.setStyles(chunkDom, defaultClass)
    }else{
        let style = activeEditor.dom.getAttrib(chunkDom, 'style')
        style = clearColor(style)
        activeEditor.dom.setAttribs(chunkDom, {
            'data-mce-style': style,
            'style': style
        })
    }
})

function replaceOrAppendCssValue(cssString, property, newValue) {
    // 构建正则表达式以匹配特定的CSS属性及后面的值
    let regex = new RegExp(`\\b${property}\\b\\s*:\\s*[^;]+\\s*;`, 'i');
    if(property === 'color') {
        regex = new RegExp(/(?<!\w-)color\s*:\s*([^\s;]+)/)
        console.log('匹配为color')
    }
    // 检查是否找到了匹配项
    if (cssString.match(regex)) {
        // 如果找到匹配项，则替换匹配到的属性值
        let newCssString = cssString.replace(regex, `${property}: ${newValue};`);
        if(property === 'color') {
            newCssString = cssString.replace(regex, `color: ${newValue}`);
        }
        console.log('匹配到已有内容',cssString,'---', newCssString)
        return newCssString
    } else {
        // 如果没有找到匹配项，则将新的属性值添加到字符串末尾
        // 如果cssString中没有结尾的分号，需要额外的逻辑来处理。
        console.log('没有匹配到已有内容,准备添加',cssString)
        return cssString.trim().endsWith(';') || !cssString
            ? `${cssString} ${property}: ${newValue};`
            : `${cssString}; ${property}: ${newValue};`;
    }
}

function clearColor(cssText) {
    const regex = /(?:color|border-color|background-color)\s*:\s*[^;]+;/g;
    const cleanedCssText = cssText.replace(regex, '')
    return cleanedCssText
}
function generateColorList(type) {
    //  生成颜色结构列表
    const colorPaletteTextList = [
        // 基础颜色
        { hex: "#000000", text: 'A' },
        { hex: "#FFFFFF", text: 'A' },
        { hex: "#d8dbe3", text: 'A' },
        { hex: "#b9becc", text: 'A' },
        { hex: "#78839c", text: 'A' },
        { hex: "#3e4d71", text: 'A' },
        { hex: "#5f483c", text: 'A' },
        { hex: "#438268", text: 'A' },
        { hex: "#5584fb", text: 'A' },

        // 深色系列
        { hex: "#63449e", text: 'A' },
        { hex: "#9d2c70", text: 'A' },
        { hex: "#cb4b45", text: 'A' },
        { hex: "#e1bc5d", text: 'A' },
        { hex: "#f49f55", text: 'A' },
        { hex: "#f18130", text: 'A' },

        // 亮色系列
        { hex: "#ea72f3", text: 'A' },
        { hex: "#4273ed", text: 'A' },
        { hex: "#7280ff", text: 'A' },
        { hex: "#2781b3", text: 'A' },
        { hex: "#0599ec", text: 'A' },
    ];
    const colorPaletteBorderList = [
        // 基础颜色
        { hex: "none", text: '/' },
        { hex: "#e5e5e5", text: '/' },
        { hex: "#c0cee7", text: '/' },
        { hex: "#f1ba66", text: '/' },
        { hex: "#6f94f1", text: '/' },
        { hex: "#ab77e8", text: '/' },
        { hex: "#ea72f3", text: '/' },
        { hex: "#7ab757", text: '/' },
        { hex: "#5584fb", text: '/' },
        { hex: "#5374c6", text: '/' }
    ];
    const colorPaletteBgList = [
        // 基础颜色
        { hex: "#FFFFFF", text: '&check;' },
        { hex: "#f5f5f5", text: '&check;' },
        { hex: "#faf3f3", text: '&check;' },
        { hex: "#fcf0e1", text: '&check;' },
        { hex: "#f8f5eb", text: '&check;' },
        { hex: "#eaf4e5", text: '&check;' },
        { hex: "#f0ebf6", text: '&check;' },
        { hex: "#eaedfa", text: '&check;' },
        { hex: "#eaedfa", text: '&check;' },
        { hex: "#eaedfa", text: '&check;' },

        // 深色系列
        { hex: "#d8d9d9", text: '&check;' },
        { hex: "#f0f0f0", text: '&check;' },
        { hex: "#f8eded", text: '&check;' },
        { hex: "#fbe8d2", text: '&check;' },
        { hex: "#fefad5", text: '&check;' },
        { hex: "#eaf2f0", text: '&check;' },
        { hex: "#dfd7f2", text: '&check;' },
        { hex: "#d5d9ff", text: '&check;' },
        { hex: "#ccdafe", text: '&check;' },
        { hex: "#cbd5ee", text: '&check;' },

        // 亮色系列
        { hex: "#b5b6b8", text: '&check;' },
        { hex: "#ebebeb", text: '&check;' },
        { hex: "#f1dbdb", text: '&check;' },
        { hex: "#f6d1a4", text: '&check;' },
        { hex: "#fdf5aa", text: '&check;' },
        { hex: "#d4e5e0", text: '&check;' },
        { hex: "#bfb0e4", text: '&check;' },
        { hex: "#aab3ff", text: '&check;' },
        { hex: "#99b5fd", text: '&check;' },
        { hex: "#98acdd", text: '&check;' },
        // 亮色系列
        { hex: "#646568", text: '&check;' },
        { hex: "#e6e6e6", text: '&check;' },
        { hex: "#e7c3c3", text: '&check;' },
        { hex: "#f0b268", text: '&check;' },
        { hex: "#fbee72", text: '&check;' },
        { hex: "#b8d3cc", text: '&check;' },
        { hex: "#957bd2", text: '&check;' },
        { hex: "#7280ff", text: '&check;' },
        { hex: "#5584fb", text: '&check;' },
        { hex: "#5374c6", text: '&check;' },
    ];
    let tempList = []
    if (type == 'text') {
        tempList = colorPaletteTextList
    } else if (type == 'bg') {
        tempList = colorPaletteBgList
    } else if (type == 'border') {
        tempList = colorPaletteBorderList
    }
    // 快捷取色块颜色列表
    if (tempList.length > 0) {
        tempList = tempList.map(item => {
            let childDom = '';
            if (type == 'text') {
                let style = `width: 18px;height: 18px;display: block;margin: 0;padding: 0;border: none;line-height: 18px;font-weight: 500;color:${item.hex}`
                childDom = `<span data-color="${item.hex}" style="border-color:#dfe0e1;background:${item.hex === '#FFFFFF' ? '#dfe0e1' : '#FFFFFF'}">
            <span style="${style}">${item.text}</span>
            </span>`
            } else if (type == 'bg') {
                let style = `width: 18px;height: 18px;margin: 0;padding: 0;border: none;line-height: 18px;font-weight: 500;color:#fff;`
                childDom = `<span data-color="${item.hex}" class="hidden-bg-color" style="background:${item.hex};border-color:${item.hex === '#FFFFFF' ? '#dfe0e1' : 'transparent'}"">
            <span style="${style}">${item.text}</span>
            </span>`
            } else if (type == 'border') {
                let style = `width: 20px;height: 20px;display: ${item.hex === 'none' ? 'block' : 'none'};margin: 0;padding: 0;border: none;line-height: 18px;font-weight: 500;color:${item.hex};z-index: 9;`
                childDom = `<span data-color="${item.hex}" style="background:transparent;border-color:${item.hex}">
            <img style="${style}" data-color="${item.hex}" src="${require('@/assets/icons/style/border-icon.png')}" />
            </span>`
            }
            return childDom
        })
    }
    return tempList.join('')
}

export {
    initPallette,
    colorPaletteClick,
    colorPalette,
    closeColorPalette

}
